// packageI/independenceBalance/mycomponent/order_pay/pay_order.js
const app = getApp();
var yz_pay = require("../../../../mycomponent/yz_pay/yz_pay");
Component({
  behaviors: [yz_pay],
  /**
     * 组件的属性列表
     */
  properties: {
    store_id: {
      type: null
    },
    show1: {
      type: null
    },
    payMuch: {
      type: null
    }
  },
  lifetimes: {
    ready() {
      this.getAgreement();
      if (this.data.show1) {
        this.confirmOrder();
      }
    }
  },
  /**
     * 组件的初始数据
     */
  data: {
    language: "",
    //是否显示支付协议
    agreementPayData: "",
    agreementPay: false,
    agreementPayShow: false,
    store_id: "",
    confirmOrderStatus: false,
    payMuch: "0",
    realname: "", //收件人
    mobile: "",
    //优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    //支付
    order_ids: "",
    income: {
      money_total: 0.0,
      sure_withdraw_money: 0.0,
    },
    store_set: {
      is_cash_pay: "",
      is_open_cashier: "",
      is_write_information: "",
    },
    payPrice: 0,
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    form: {
      mobile: "",
      realname: "",
    },
    allData: {},
    order_data: "",
    loadDiscount: false,
    goods_price: 0.0,
    dispatch_price: 0.0,
    discount_price: 0,
    price: 0.0,
    deduction_price: 0,
    payType: [],
    typename: "",
    show1: false,
    clicktag: 0,
    uid: "",
    cashier_type: "",
    hotel_id: "",
    order_pay_id: "",

    //消费红包
    showPacket: false,
    redirectData: {},
  },

  /**
     * 组件的方法列表
     */
  methods: {
    fromChild(e) {
      if (this.data.money == '0.00' || e.detail.money == '0.00') {
        this.submit('54');
      } else {
        let datas = e.detail.submitArr;
        this.submit(datas);
      }
    },
    onClickHide() {
      this.setData({
        showPacket: false,
      });
      this.toRedirect();
    },
    toPacket() {
      wx.redirectTo({
        url: "/packageE/ConsumePacket/ConsumePacketSuccess/ConsumePacketSuccess?order_id=" + this.data.order_ids.toString(),
      });
    },
    // 消费红包
    checkoutConsumePacket() {
      let that = this;
      this.getVoiceSet();
      let basicinfo = wx.getStorageSync("yz_basic_info");
      if (basicinfo && basicinfo.globalParameter && basicinfo.globalParameter.consume_red_packet_status == 1) {
        let urlStr = app.getNetAddresss("plugin.consume-red-packet.Frontend.Modules.Packet.Controllers.has.index");
        app._postNetWork({
          url: urlStr,
          data: {
            order_id: this.data.order_ids.split(","),
          },
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              this.setData({
                show1: false,
                showPacket: true,
              });
              that.triggerEvent('showOff', {
                'show1': this.data.show1
              });
            } else {
              this.toRedirect();
            }
          },
          fail: (res) => {
            this.toRedirect();
            console.log(res);
          },
        });
      } else {
        this.toRedirect();
      }
    },
    toRedirect() {
      wx.showToast({
        icon: "none",
        title: "支付成功",
        duration: 2000,
      });
      if (this.data.order_sn) {
        this.payCallBack();
      }
      // wx.showModal({
      //   title: "提示",
      //   content: "支付成功",
      //   showCancel: false,
      //   success: (res) => {
      //     if (res.confirm) {
      //       if (this.data.redirectData.cashPay) {
      //         wx.reLaunch({
      //           url: "/packageG/member_v2/member_v2",
      //         });
      //       } else if (!app._isTextEmpty(this.data.min_redirect_url)) {
      //         try {
      //           wx.redirectTo({
      //             url: this.data.min_redirect_url,
      //           });
      //         } catch (e) {
      //           console.log(e);
      //         }
      //       } else {
      //         wx.reLaunch({
      //           url: "/packageG/index/index",
      //         });
      //       }
      //     }
      //   },
      // });
    },
    getVoiceSet() {
      //判断是否开启语音播报
      // let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.cashier.voice.index");
      app._postNetWork({
        url: urlStr,
        data: {
          order_id: this.data.order_ids,
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            // const bgMusic = wx.createInnerAudioContext();
            const bgMusic = wx.getBackgroundAudioManager(); //音乐播放实例
            // //bug ios 播放时必须加title 不然会报错导致音乐不播放
            bgMusic.title = "支付成功语音提示";
            bgMusic.src = res.data.url;
            bgMusic.play();
            // bgMusic.src = `data:audio/x-wav;base64,${res.data.speech}`;
            // bgMusic.src = 'https://dev4.yunzmall.com/attachment/audios/0/2021/05/556f15b68d5d2c1886e2e470e6f1cda9.mp3'
          } else {
            console.log(res);
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },

    PayShowbtn() {
      this.setData({
        agreementPayShow: false,
      });
    },
    //处理按键
    _handleKeyPress(e) {
      let num = e.currentTarget.dataset.num;
      //不同按键处理逻辑
      // -1 代表无效按键，直接返回
      if (num == -1) return false;
      switch (String(num)) {
      //小数点
      case ".":
        this._handleDecimalPoint();
        break;
        //删除键
      case "D":
        this._handleDeleteKey();
        break;
        //确认键
      case "S":
        this._handleConfirmKey();
        break;
      default:
        this._handleNumberKey(num);
        break;
      }
    },
    //处理小数点函数
    _handleDecimalPoint() {
      //如果包含小数点，直接返回
      if (this.data.payMuch.indexOf(".") > -1) {
        return false;
      }
      //如果小数点是第一位，补0
      if (!this.data.payMuch.length) {
        this.setData({
          payMuch: "0.",
        });
      } else {
        //如果不是，添加一个小数点
        this.setData({
          payMuch: this.data.payMuch + ".",
        });
      }
    },
    //处理删除键
    _handleDeleteKey() {
      let S = this.data.payMuch;
      //如果没有输入，直接返回
      if (S.length <= 1) {
        this.setData({
          payMuch: "0",
        });
        return;
      }
      //否则删除最后一个
      this.setData({
        payMuch: S.substring(0, S.length - 1),
      });
    },
    _handleConfirmKey() {
      let S = this.data.payMuch;
      //未输入
      if (!S.length || Number(S) === 0) {
        wx.showToast({
          icon: "none",
          title: "您目前未输入!",
          duration: 1500,
        });
        return false;
      }
      //将 8. 这种转换成 8.00
      if (S.indexOf(".") > -1 && S.indexOf(".") === S.length - 1) {
        S = Number(S.substring(0, S.length - 1)).toFixed(2);
      }
      //保留两位
      S = Number(S).toFixed(2);
      this.setData({
        payMuch: S,
      });
      this.confirmOrder();
    },
    confirmOrder() {
      var val = this.data.payMuch;
      if (val && val > 0) {
        this.setData({
          payPrice: val,
          confirmOrderStatus: true,
          isdisabled: true,
        });
        this.preGoodsBuy();
      } else {
        wx.showToast({
          icon: "none",
          title: "请输入正确的付款金额!",
          duration: 1500,
        });
        this.setData({
          confirmOrderStatus: false,
          isdisabled: false,
        });
      }
    },
    //处理数字
    _handleNumberKey(num) {
      let S = this.data.payMuch;
      //如果有小数点且小数点位数不小于2
      if (S.indexOf(".") > -1 && S.substring(S.indexOf(".") + 1).length < 2) {
        this.setData({
          payMuch: S + num,
        });
      }
      //没有小数点
      if (!(S.indexOf(".") > -1)) {
        //如果第一位是0，只能输入小数点
        if (num == 0 && S.length == 0) {
          this.setData({
            payMuch: "0.",
          });
        } else {
          if (S.length && Number(S.charAt(0)) === 0) {
            this.setData({
              payMuch: num,
            });
            return;
          }
          this.setData({
            payMuch: S + num,
          });
        }
      }
    },
    //直接购买
    preGoodsBuy() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.balance.goodsBuy.index");
      urlStr += "&price=" + this.data.payPrice;
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&member_coupon_ids=" + this.assembleCoupons();
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());

      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._getNetWork({
          url: urlStr,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              if (res.data.balance) {
                that.setData({
                  balanceNow: res.data.balance
                });
              }
              that.setViewData(res.data); //设置界面
              // if (that.data.cashier_type != "hotel") {
              that.initCoupon(res.data.discount); //设置优惠券信息
              // }
              that.initPayType();
            } else {
              wx.showModal({
                title: "提示",
                content: res.msg,
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.navigateBack({
                      delta: 1,
                    });
                  }
                },
              });
            }
            setTimeout(function () {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
    //组装优惠券json信息
    assembleCoupons() {
      let coupons = [];
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        coupons.push(this.data.checkCouponList[i].id);
      }
      return coupons;
    },
    //组装优惠抵扣信息
    assembleDeduction() {
      let deductions = [];
      for (let i = 0; i < this.data.checkDeductionList.length; i++) {
        deductions.push(this.data.checkDeductionList[i]);
      }
      return deductions;
    },
    //设置界面
    setViewData(data) {
      // console.log(data.orders, '55454');
      this.setData({
        allData: data,
        order_data: data.orders,
        loadDiscount: true,
        goods_price: data.total_goods_price, //设置商品总价格
        dispatch_price: data.total_dispatch_price, //设置总运费价格
        deduction_price: data.total_deduction_price, //设置总抵扣价格
        price: data.total_price, //设置总价格（合计）
        // 服务费
        service: data.orders[0].order_fees,
        datas: data.orders[0],
      });
      if (this.data.cashier_type != "hotel") {
        this.setData({
          discount_price: data.total_discount_price, //设置总优惠价格
        });
      }
    },
    //初始化优惠券
    initCoupon(data) {
      this.setData({
        isShowCoupon: data.whether_show_coupon == "1" ? true : false,
      });
      let coupon = data.member_coupons;
      if (coupon != undefined && coupon != "" && coupon != null) {
        this.setData({
          coupon_size: coupon.length,
        });
      }
      this.setData({
        coupons: coupon,
      });
    },
    initPayType() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.balance.payment.getList");
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&price=" + this.data.payMuch;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let payTypeData = res.data;
            let arr = {};
            arr.buttons = res.data;
            that.hanleIcon(arr);
            that.setData({
              payType: payTypeData,
              typename: "支付",
              show1: true,
            });
            that.triggerEvent('showOff', {
              'show1': that.data.show1
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
              success: function () {
                setTimeout(function () {
                  //要延时执行的代码
                  wx.navigateBack({
                    delta: 1,
                  });
                }, 1500); //延迟时间
              },
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    btnstyle(type) {
      if (type == 1 || type == 6 || type == 9 || type == 12 || type == 20 || type == 22) {
        return "#64b42e";
      } else if (type == 2 || type == 7 || type == 10 || type == 15 || type == 21) {
        return "#069ce7";
      } else if (type == 3) {
        return "#fc992c";
      } else if (type == 14) {
        return "#e36724";
      } else if (type == 18) {
        return "#dedede";
      } else {
        return "#fac337";
      }
    },
    btnclass(type) {
      if (type == 1 || type == 6 || type == 9 || type == 12 || type == 20 || type == 22) {
        return "icon-pay_b";
      } else if (type == 2 || type == 7 || type == 10 || type == 15 || type == 21) {
        return "icon-pay_c";
      } else if (type == 3) {
        return "icon-pay_d";
      } else if (type == 14) {
        return "icon-pay_f";
      } else if (type == 18) {
        return "card";
      } else {
        return "icon-pay_a";
      }
    },
    show1btn() {
      this.setData({
        show1: false,
      });
      this.triggerEvent('showOff', {
        'show1': this.data.show1
      });
    },
    //抵扣选择响应
    discountHandle(e) {
      let bol = e.detail;
      let code = e.currentTarget.dataset.d.code;
      let index = e.currentTarget.dataset.index;

      console.log(this.data.order_data[0], this.data.order_data[0].order_deductions[index]);
      //处理选择
      this.screenDiscount(this.data.order_data[0], {
        checked: bol,
        code: code,
      });
      //重新计算
      this.preGoodsBuy(); //直接购买
    },
    //筛选抵扣
    screenDiscount(item, value) {
      this.deductionListHandle(item, value);
    },
    deductionListHandle(item, value) {
      let checkDeductionList = this.data.checkDeductionList;
      // let service_fee = this.data.service_fee;
      // let note = this.data.note;
      let isHasPreId = false;

      if (checkDeductionList.length > 0) {
        checkDeductionList.forEach((deduction, index) => {
          if (deduction && deduction.pre_id == item.pre_id) {
            isHasPreId = true;
            if (value && value.checked) {
              // 选中的时候检查是否有对应的code
              if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) == -1) {
                deduction.deduction_ids.push(value.code);
              }
            } else if (value && !value.checked) {
              // 取消选中的时候检查去掉对应的code
              if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) > -1) {
                deduction.deduction_ids.splice(deduction.deduction_ids.indexOf(value.code), 1);
              }
            }

            // 留言和安装选项重新赋值
            // deduction.note = note[item.pre_id];
            // deduction.service_fee = service_fee[item.pre_id];
          }
        });
      }
      if (!isHasPreId) {
        checkDeductionList.push({
          deduction_ids: value && value.code ? [value.code] : [],
          pre_id: item.pre_id,
        });
      }
      this.setData({
        checkDeductionList
      });
      // console.log('checkDeductionList:', this.data.checkDeductionList)
    },
    //优惠券
    showCoupon() {
      if (this.data.coupon_size == 0) {
        wx.showToast({
          icon: "none",
          title: "暂无优惠券使用",
          duration: 1500,
        });
        return;
      }
      this.setData({
        popupCouponSpecs: true,
      });
    },
    //选择优惠券
    selectCoupon(e) {
      let couponBol = e.detail;
      let index = e.currentTarget.dataset.index;
      // let item = e.currentTarget.dataset.item;
      this.setData({
        ["coupons[" + index + "].checked"]: couponBol,
      });
      //处理选择
      //因为换了组件改调用方法
      this.screenCoupon(couponBol, this.data.coupons[index]);
      //设置view
      this.setCouponView();
      //重新计算
      this.preGoodsBuy(); //直接购买
    },
    //筛选数据优惠券状态
    screenCoupon(value, valObj) {
      var tarValue = valObj;
      if (value) {
        //选中添加
        if (this.data.checkCouponList.length > 0) {
          for (let i = 0; i < this.data.checkCouponList.length; i++) {
            if (this.data.checkCouponList[i].id == tarValue.id) {
              this.data.checkCouponList.splice(i, 1);
            }
          }
          let checkCouponList = this.data.checkCouponList;
          checkCouponList.push(tarValue);
          this.setData({
            checkCouponList: checkCouponList,
          });
        } else {
          let checkCouponList = this.data.checkCouponList;
          checkCouponList.push(tarValue);
          this.setData({
            checkCouponList: checkCouponList,
          });
        }
      } else {
        //取消选中
        if (this.data.checkCouponList.length > 0) {
          for (let i = 0; i < this.data.checkCouponList.length; i++) {
            if (this.data.checkCouponList[i].id == tarValue.id) {
              let checkCouponList = this.data.checkCouponList;
              checkCouponList.splice(i, 1);
              this.setData({
                checkCouponList: checkCouponList,
              });
            }
          }
        }
      }
    },
    //设置view
    setCouponView() {
      this.setData({
        use_coupon_size: this.data.checkCouponList.length,
      });
    },
    //关闭优惠卷
    couponclose() {
      this.setData({
        popupCouponSpecs: false,
      });
    },
    realnameinp(e) {
      let val = e.detail.value;
      this.setData({
        "form.realname": val,
      });
    },
    mobileinp(e) {
      let val = e.detail.value;
      this.setData({
        "form.mobile": val,
      });
    },
    agreementPayinp(e) {
      let bol = e.detail;
      this.setData({
        agreementPay: bol,
      });
    },
    showPay() {
      this.setData({
        agreementPayShow: true,
      });
    },

    //提交订单
    submit(btn) {
      let val = btn;
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.balance.create.index");
      urlStr += "&price=" + this.data.payMuch;
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&member_coupon_ids=" + JSON.stringify(this.assembleCoupons());
      urlStr += "&orders=" + JSON.stringify(this.assembleDeduction());
      // urlStr += "&mobile=" + this.data.form.mobile;
      // urlStr += "&realname=" + this.data.form.realname;

      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        if (this.data.agreementPayData) {
          if (!this.data.agreementPay) {
            this.setData({
              clicktag: 0,
            });
            wx.showToast({
              icon: "none",
              title: "请先勾选支付协议",
              duration: 1500,
            });
            return;
          }
        }

        app._getNetWork({
          url: urlStr,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                order_ids: res.data.order_ids,
              });
              that.getMultipleOrderInfo(val);
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
              that.data.isPayClick = false;
            }
            setTimeout(function () {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
    //多订单合并支付获取信息接口方法
    getMultipleOrderInfo(val) {
      let urlStr = app.getNetAddresss("order.merge-pay");
      urlStr += "&order_ids=" + this.data.order_ids;
      urlStr += "&pid=" + this.data.uid;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              order_sn: res.data.order_pay.pay_sn,
              balance: res.data.member.credit2,
              money: res.data.order_pay.amount,
              uid: res.data.order_pay.uid,
              order_pay_id: res.data.order_pay.id,
              buttons: res.data.buttons,
              min_redirect_url: res.data.min_redirect_url,
            });
            this.handlePay(val, val.value);
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg,
              success(res) {
                if (res.confirm) {
                  wx.reLaunch({
                    url: "/packageG/index/index",
                  });
                  console.log("用户点击确定");
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });
            this.data.isPayClick = false;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    getAgreement() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.cashier.center.getPaySet");
      let json = {
        store_id: this.data.store_id,
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              agreementPayData: res.data.get_pay_protocol,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
  }
});